#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

int pathSum(TreeNode* root, int target) {
    if (!root)   return 0;
    int res = rootSum(root, target);
    res += pathSum(root->left, target);
    res += pathSum(root->right, target);
    return res;
}
int rootSum(TreeNode* root, long long target)
{
    if (!root)   return 0;
    int res = 0;
    if (root->val == target) res++;

    res += rootSum(root->left, target - root->val);
    res += rootSum(root->right, target - root->val);
    return res;
}

int maxPathSum(TreeNode* root) {
    int res = INT_MIN;
    auto dfs = [&](auto&& dfs, TreeNode* root)->int {
        if (!root)   return 0;
        int l = max(0, dfs(dfs, root->left));
        int r = max(0, dfs(dfs, root->right));
        res = max(res, l + r + root->val);
        return max(l, r) + root->val;
    };
    dfs(dfs, root);
    return res;
}